﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;

namespace Sinacor.Tools.Web.ConstantesErro
{
    public abstract class BasePage : System.Web.UI.Page
    {
        protected string usuario = string.Empty;
        
        
        protected virtual void Page_Load(object sender, EventArgs e)
        {
            validaUsuario();
            if (!this.Page.IsPostBack)
            {
                validaPermissao();
            }
        }

        protected void validaUsuario()
        {
            if (Session["user"] == null || Convert.ToString(Session["user"]).Trim() == string.Empty)
            {
                if (this.Page.ToString().ToLower().IndexOf("login") == -1)
                {
                    Server.Transfer("frmLogin.aspx");
                }
            }
        }


        private void validaPermissao()
        {
            if (!Negocio.Permissoes.usuarioPossuiPermissaoPagina(this.Page.ToString().Replace("_", ".").Replace("ASP.", string.Empty), Convert.ToString(Session["user"]).Trim(), this.getPath() + "Permission.xml"))
            {
                this.Page.Server.Transfer("PermissaoNegada.htm");
            }
        }

        private string getPath()
        {
            string caminho = Page.Server.MapPath("~");
            if (caminho.LastIndexOf('\\') != caminho.Length - 1)
                caminho += "\\";

            return caminho;
        }

        protected void carregar(Menu menu)
        {
            XmlDocument doc = new XmlDocument();
            MenuItem menuItem = null;
            string nomeArquivo = this.getPath() + "Menu.xml";

            if (!System.IO.File.Exists(nomeArquivo)) throw new Exception("O arquivo Menu.xml não foi encontrado no seguinte diretório: " + this.getPath());

            doc.Load(nomeArquivo);
            XmlNode no = doc.SelectSingleNode("/menu");
            int qtdeLoops = no.ChildNodes.Count;
            for (int i = 0; i < qtdeLoops; i++)
            {
                menuItem = new MenuItem(no.ChildNodes[i].Attributes["valor"].InnerText, no.ChildNodes[i].Attributes["texto"].InnerText);

                menu.Items.Add(menuItem);

                if (no.ChildNodes[i]["menu"] != null)
                    this.carregarMenu(menuItem, no.ChildNodes[i]["menu"], string.Empty);
            }
        }

        protected void carregarMenu(MenuItem menu, XmlNode no, string target)
        {
            XmlNode noItem;
            MenuItem menuItem = null;
            int qtdeLoops = no.ChildNodes.Count;
            for (int i = 0; i < qtdeLoops; i++)
            {
                noItem = no.ChildNodes[i];
                menuItem = new MenuItem(noItem.Attributes["valor"].InnerText, noItem.Attributes["texto"].InnerText);
                menuItem.Target = target;
                if (noItem.Attributes["caminho"] != null && noItem.Attributes["valor"].InnerText != null)
                {
                    menuItem.NavigateUrl = "javascript:clicou('" + noItem.Attributes["caminho"].InnerText + "');";
                }
                menu.ChildItems.Add(menuItem);


                if (noItem["menu"] != null)
                    this.carregarMenu(menuItem, noItem["menu"], target);
            }
        }

        private string msg = string.Empty;
        public string Msg
        {
            get { return this.msg; }
        }

        protected virtual void apresentarMensagem(string mensagem)
        {
            mensagem = mensagem.Replace("'", string.Empty).Replace(Environment.NewLine, string.Empty).Replace("\\n", string.Empty).Replace("\n", string.Empty).Replace("\\", "\\\\");
            this.msg = mensagem;
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "mensagem", "alert('" + mensagem + "');", true);
            //Response.Write("<script type=\"text/javascript\">showalert('" + mensagem + "');</script>");
            
        }

        protected abstract void preencherGrid();
        protected abstract void preencherGrid(string sortExpression);

        protected virtual void paginar(object sender, GridViewPageEventArgs e)
        {
            ((GridView)sender).PageIndex = e.NewPageIndex;
            this.preencherGrid();            
        }

        protected void setGridCellStyle(GridViewRow linha, bool whiteText)
        {
            int qtdeLoops = linha.Cells.Count;
            for (int i = 0; i < qtdeLoops; i++)
            {
                linha.Cells[i].BorderColor = System.Drawing.Color.Black;
                linha.Cells[i].ForeColor = whiteText ? System.Drawing.Color.White : linha.Cells[i].ForeColor;
            }
        }

        protected void setDefaultGridStyle(GridViewRowEventArgs e, string defaultStyle)
        {
            e.Row.CssClass = defaultStyle.ToUpper();
            e.Row.Attributes.Add("onmouseover", "this.className = 'HOVER';");
            e.Row.Attributes.Add("onmouseout", "this.className = '" + defaultStyle.ToUpper() + "';");
            e.Row.Attributes.Add("onclick", "javascript:setUpdateItem(this);");
        }

        

    }
}
